package cn.edu.hbwe.book.servlet.user;


import java.io.IOException;

import javax.security.auth.login.LoginException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.service.UserService;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取登录页面的用户名和密码
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				//2.调用service来判断用户名和密码是否正确
				UserService service = new UserService();
				User user;
				try {
					//System.out.println("test");
					user = service.login(username,password);
					if (user.getState() == 1) {//如果用户的状态为激活，才允许登录
						request.getSession().setAttribute("user", user);
						//用户为超级管理员则跳转到后台界面
						String role = user.getRole();
						if (role.equals("超级用户")) {
							request.getRequestDispatcher("BooksListServlet").forward(request, response);
							return;
						} else {
							response.sendRedirect(request.getContextPath() + "/client/myAccount.jsp");
							return;
						}
					}} catch (cn.edu.hbwe.book.exception.LoginException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("register message", e.getMessage());
					request.getRequestDispatcher("BooksListServlet").forward(request, response);
					return;
				}
	}
}
